package cn.istartfinancial.util;


import cn.istartfinancial.exception.MyException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author: Nzp
 * @date: 2018/8/22
 * @description: 对象数据校验工具类
 */
public class ValidatorUtils
{
    private static Validator validator;

    static
    {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws MyException 校验不通过，则报BusinessException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws MyException
    {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty())
        {
            ConstraintViolation<Object> constraint =
                    (ConstraintViolation<Object>) constraintViolations.iterator().next();
            throw new MyException(constraint.getMessage());
        }
    }
}
